import { NameSpace } from 'utils';
import exceed from 'utils/apimap';
import CONSTANTS from 'utils/constants.js';

const ns = NameSpace('groupIndex');
export const RECEIVE_GROUP_SETTING = ns('RECEIVE_GROUP_SETTING');
export const RECEIVE_GROUP_LIST = ns('RECEIVE_GROUP_LIST');
export const RECEIVE_GROUP_SUBLIST = ns('RECEIVE_GROUP_SUBLIST');
export const UPDATE_GROUP_SUBLIST = ns('UPDATE_GROUP_SUBLIST');
export const SET_NAVKEY = ns('SET_NAVKEY');
export const UPDATE_DATA = ns('UPDATE_DATA');
export const RESET_DATA = ns('RESET_DATA');

const { organization } = window.FORCE;
export function setNavKey(data) {
  return (dispatch) => {
    dispatch({
      type: SET_NAVKEY,
      data: data || 'mine',
    });
  };
}

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

export function resetData() {
  return (dispatch) => {
    dispatch({
      type: RESET_DATA,
    });
  };
}

// 将指定id的状态恢复初始值
export function updateSubGroupMap(id) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_GROUP_SUBLIST,
      data: id,
    });
  };
}

export function updateSubGroupMapWithSearch(id) {
  return (dispatch, getState) => {
    const state = getState().organization.groups;
    const { subGroupMap } = state;
    if (subGroupMap[id]) {
      subGroupMap[id].isExpanded = !subGroupMap[id].isExpanded;
      updateData({
        subGroupMap,
      })(dispatch);
    }
  };
}

function handleData(list) {
  const parentGroupList = [];
  const subGroupMap = {};
  list.forEach((item) => {
    // 是否有父组在列表中
    const hasParentGroup = list.some((v) => {
      return item.parent_id === v.id;
    });
    if (hasParentGroup) {
      const { parent_id } = item;
      if (!subGroupMap[parent_id]) {
        subGroupMap[parent_id] = {
          list: [item],
          total: 1,
          isLoadingSubGroup: false,
          isExpanded: true,
        };
      } else {
        subGroupMap[parent_id].list.push(item);
        subGroupMap[parent_id].total += 1;
      }
    } else {
      parentGroupList.push(item);
    }
  });
  return { parentGroupList, subGroupMap };
}

export function getGroupsCount(per_page) {
  return (dispatch, getState) => {
    const state = getState().organization.groups;
    const { order_by, navKey, search } = state;

    const promises = [
      exceed.fetch({
        api: 'groups.mine.list',
        data: {
          page: 1,
          // 暂不分页，总共一百
          per_page: per_page || 10,
          order_by,
          parent_id: organization.namespace_id,
          search,
        },
      }),
      exceed.fetch({
        api: 'groups.all.list',
        data: {
          page: 1,
          per_page: per_page || 10,
          order_by,
          parent_id: organization.namespace_id,
          search,
        },
      }),
    ];

    updateData({
      isLoading: true,
    })(dispatch);

    Promise.all(promises)
      .then((result) => {
        const res = navKey === 'mine' ? result[0] : result[1];
        const groupList = res.slice(1);
        const total = res[0].amount;
        // 如果是搜索，需要将数据分为2部分： 当前列表有父组的和无父组的
        const { parentGroupList, subGroupMap } = handleData(groupList);
        const extraData = {};
        if (search) {
          extraData.groupList = parentGroupList;
          extraData.subGroupMap = subGroupMap;
        }
        updateData({
          groupList,
          total,
          totalMine: result[0][0].amount,
          totalAll: result[1][0].amount,
          currentPage: 1,
          isLoading: false,
          ...extraData,
        })(dispatch);
      })
      .catch((err) => {
        updateData({
          isLoading: false,
        })(dispatch);
        console.error(err);
      });
  };
}

export function getGroups(page, per_page) {
  return (dispatch, getState) => {
    const state = getState().organization.groups;
    const { order_by, navKey, search } = state;

    const fetchParams = {
      api: navKey === 'mine' ? 'groups.mine.list' : 'groups.all.list',
      data: {
        page,
        // 暂不分页，总共一百
        per_page: per_page || 10,
        order_by,
        parent_id: organization.namespace_id,
        search,
      },
    };

    updateData({
      isLoading: true,
    })(dispatch);

    const promise = new Promise((resolve, reject) => {
      exceed
        .fetch(fetchParams)
        .then((result) => {
          resolve(result);
        })
        .fail((err) => {
          reject(err);
        });
    });

    promise
      .then((res) => {
        const groupList = res.slice(1);
        const total = res[0].amount;
        // 如果是搜索，需要将数据分为2部分： 当前列表有父组的和无父组的
        const { parentGroupList, subGroupMap } = handleData(groupList);
        const extraData = {};
        if (search) {
          extraData.groupList = parentGroupList;
          extraData.subGroupMap = subGroupMap;
        }
        updateData({
          groupList,
          total,
          currentPage: page,
          isLoading: false,
          ...extraData,
        })(dispatch);
      })
      .catch((err) => {
        updateData({
          isLoading: false,
        })(dispatch);
        console.error(err);
      });
  };
}

// 根据id获取子组列表
export function getSubGroups(id) {
  return (dispatch, getState) => {
    const state = getState().organization.groups;
    const { order_by } = state;

    const fetchParams = {
      api: 'group.subgroups.list',
      data: {
        page: 1,
        per_page: CONSTANTS.DEFAULT_PAGE_SIZE,
        order_by,
      },
      params: {
        id,
      },
    };

    dispatch({
      type: RECEIVE_GROUP_SUBLIST,
      data: {
        [id]: {
          list: [],
          total: 0,
          isLoadingSubGroup: true,
          isExpanded: false,
        },
      },
    });

    const promise = new Promise((resolve, reject) => {
      exceed
        .fetch(fetchParams)
        .then((result) => {
          resolve(result);
        })
        .fail((err) => {
          reject(err);
        });
    });

    promise
      .then((res) => {
        const list = res.slice(1);
        const total = res[0].amount;
        dispatch({
          type: RECEIVE_GROUP_SUBLIST,
          data: {
            [id]: {
              list,
              total,
              isLoadingSubGroup: false,
              isExpanded: true,
            },
          },
        });
      })
      .catch((err) => {
        dispatch({
          type: RECEIVE_GROUP_SUBLIST,
          data: {
            [id]: {
              list: [],
              total: 0,
              isLoadingSubGroup: false,
              isExpanded: false,
            },
          },
        });
        console.error(err);
      });
  };
}

// 查询企业组设置
export function getGroupSettingData() {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'organization.group.setting.get',
        params: {
          org_id: organization.id,
        },
      })
      .then((result) => {
        dispatch({
          type: RECEIVE_GROUP_SETTING,
          data: result,
        });
      });
  };
}
